package com.xxx.nio.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

public class EchoClient {
    private final String host;
    private final int port;

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        new EchoClient("localhost", 8080).start();
    }

    public void start() throws Exception {
        // 事件处理线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // Bootstrap：Netty客户端
            Bootstrap b = new Bootstrap();
            b.group(group)      // 客户端这里只需要绑定一个线程组（相比Server端少了监听线程组）
             .channel(NioSocketChannel.class)    // 指定客户端的Channel类型，NioSocketChannel为非阻塞IO模型
             .remoteAddress(new InetSocketAddress(host, port))     // 绑定远程Netty服务端地址和端口
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) {   // 初始化Channel
                     ch.pipeline().addLast(new EchoClientHandler());    // 添加自定义业务处理handler到ChannelPipeline
                 }
             });

            // 异步地绑定服务器;调用sync方法阻塞等待直到连接完成
            ChannelFuture f = b.connect().sync();
            // 获取Channel的CloseFuture，并且阻塞当前线程直到它完成
            f.channel().closeFuture().sync();
        } finally {
            // 优雅地关闭EventLoopGroup，释放所有的资源
            group.shutdownGracefully();
        }
    }
}
